X=imread('wed2.jpg');
r=X(:,:,1);g=X(:,:,2);b=X(:,:,3);
Xgray=0.2126*r + 0.7152*g +0.0722*b; %2-dimensional array
original=figure;
set(original, 'name', 'Original BW','numbertitle','off')
imagesc(Xgray);colormap(gray)
axis square;
JPEG = [16, 11, 10, 16, 24, 40, 51, 61;
        12, 12, 14, 19, 26, 58, 60, 55;
        14, 13, 16, 24, 40, 57, 69, 56;
        14, 17, 22, 29, 51, 87, 80, 62;
        18, 22, 37, 56, 68, 109, 103, 77;
        24, 35, 55, 64, 81, 104, 113, 92;
        49, 64, 78, 87, 103, 121, 120, 101;
        72, 92, 95, 98, 112, 100, 103, 99];

for i=1:75
    for j=1:75
        x=Xgray((i-1)*8+1:(i-1)*8+8,(j-1)*8+1:(j-1)*8+8); %extract 8x8 pixel block

        %Start of Compression Process
        xd=double(x); %convert uint8 to double
        xc=xd-128; %center matrix over zero
        Y=dct(dct(xc')'); %Apply the 2D-DCT, then Y is the transform matrix

        p=1;    %p is the loss parameter
        Q=p*JPEG; %use JPEG-suggested matrix to define the linear quantization matrix
        Yq=round(Y./Q); %replace Y by the compressed matrix (Quantize)

        %Start of Decompression Process
        Ydq=Yq.*Q; %dequantization
        Xdq=idct2(Ydq); %inverse DCT transform
        Xe=Xdq+128; %un-center
        Xf=uint8(Xe); %convert back to uint8
        Xout((i-1)*8+1:(i-1)*8+8,(j-1)*8+1:(j-1)*8+8)=Xf;

    end
end

figure('name', 'After, p=1, JPEG suggested Matrix','numbertitle','off');
imagesc(Xout);colormap(gray) %display the 8x8 block after compression
axis square